import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:xin_he/page/home/model/xin_he_goods_item_detail_entity.dart';
import 'package:xin_he/page/home/model/xin_he_goods_item_entity.dart';
import 'package:xin_he/page/shopping_car/xin_he_goods_payment/xin_he_payment_methods_model.dart';
import 'package:xin_he/routes/xin_he_routes.dart';

import '../../../service/xin_he_reqest.dart';
import '../../../utils/xin_he_UI_constancs.dart';
import '../../../utils/xin_he_storage.dart';
import '../../../utils/xin_he_toast.dart';
import 'xin_he_instant_pay_state.dart';

class XinHeInstantPayLogic extends GetxController {
  final XinHeInstantPayState state = XinHeInstantPayState();

  List iconList = ['pay_method_alipay','pay_method_wechat','pay_method_redbag_small','pay_method_shopping','pay_method_mengya','pay_method_oil','pay_method_alipay'];
  List titleList = ['支付宝','微信','消费金红包','购物金','未解冻云茶籽','茶油卡','余额'];
  RxInt selectedIndex = 0.obs;
  RxList payMethodsList = [].obs;

  RxList realPayList = [].obs;
  final payScene   =  PayScene.none.obs;
  Map orderMap = {};
  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();


    List item = [];
    for(int i=0;i<iconList.length;i++){
       Map<String,dynamic> map = {
         'icon':iconList[i],
         'title':titleList[i],
         'id':i
       };

       XinHePaymentMethodModel model = XinHePaymentMethodModel.fromJson(map);
       item.add(model);
    }
    payMethodsList.value = item;
  }

  List getRealPayList(int type){

    if(payMethodsList.isNotEmpty){
      ///清理状态
      payMethodsList.clear();
      List item = [];
      for(int i=0;i<iconList.length;i++){
        Map<String,dynamic> map = {
          'icon':iconList[i],
          'title':titleList[i],
          'id':i
        };

        XinHePaymentMethodModel model = XinHePaymentMethodModel.fromJson(map);
        item.add(model);
      }
      payMethodsList.value = item;
    }

    realPayList.value.clear();
    if(type== 0){
      XinHePaymentMethodModel model = payMethodsList[6];
      model.selected = true;
      realPayList.add(model);
      realPayList.add(payMethodsList[0]);
      realPayList.add(payMethodsList[1]);

    }
    if(type== 1){
      XinHePaymentMethodModel model = payMethodsList[6];
      model.selected = true;
      realPayList.add(model);
      realPayList.add(payMethodsList[0]);
      realPayList.add(payMethodsList[1]);

    }
    if(type== 2){
      XinHePaymentMethodModel model = payMethodsList[6];
      model.selected = true;
      realPayList.add(model);
      realPayList.add(payMethodsList[0]);
      realPayList.add(payMethodsList[1]);
      realPayList.add(payMethodsList[2]);
      realPayList.add(payMethodsList[3]);

    }
    if(type== 3){

      XinHePaymentMethodModel model = payMethodsList[6];
      model.selected = true;
      realPayList.add(model);
      realPayList.add(payMethodsList[0]);
      realPayList.add(payMethodsList[1]);
      realPayList.add(payMethodsList[2]);
      realPayList.add(payMethodsList[3]);

    }
    if(type== 4){
      XinHePaymentMethodModel model = payMethodsList[5];
      model.selected = true;
      realPayList.add(model);

    }

    ///认养树
    if(type == 5) {
      XinHePaymentMethodModel model = payMethodsList[6];
      model.selected = true;
      realPayList.add(model);
      realPayList.add(payMethodsList[0]);
      realPayList.add(payMethodsList[1]);
    }
    return realPayList.value;
  }



  getPayChannel(title) {
    String channel = '';
    if(title == '余额') {
      channel = 'BALANCE';
    }
    else if(title == '支付宝') {
      channel = 'ZHIFUBAO_PAY';
    }
    else if(title == '微信') {
      channel = 'WEIXIN_PAY';
    }else {
      channel = 'ZHIFUBAO_PAY';

    }
    

    return channel;
  }

  requestPayOrder() async {

    XinHePaymentMethodModel model =    realPayList[selectedIndex.value] ;
    var userId = await XinHeLocalStorage.get(XinHeStorage.userId);

    Map<String,dynamic>map = {
      'userId': userId,
      'orderId':orderMap['orderId'],
      // 'payChannel':getPayChannel(model.title)
      'payChannel': 'BALANCE'

    };

    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/orderPay/requestPayOrder',params: map,isPostAndwwwForm: true);

    if(!result.result){
      XinHeToast.center(result.data['message']);
      return ;
    }

    if(result.data['code'] == 0) {

        Get.back();
        if(payScene.value == PayScene.fromGoodsCartOrder) {
          Get.offNamed(XinHeRoutes.placeOrderSuccess,arguments: orderMap);
        }

      launchWebUrl('alipays://platformapi/startapp?saId=10000007&qrcode=' + result.data['data']);

    }else {

      XinHeToast.center(result.data['message']);

    }



  }



  requestTreeOrder() async {

    XinHePaymentMethodModel model =    realPayList[selectedIndex.value] ;

    Map<String,dynamic>map = {
      'orderId':orderMap['orderId'],
      // 'payChannel':getPayChannel(model.title)
      'payChannel': 'ZHIFUBAO_PAY'

    };

    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/adoptedTreeOrder/requestTreePay',params: map,isPostAndwwwForm: true);

    if(!result.result){
      XinHeToast.center(result.data['message']);
      return ;
    }

    if(result.data['code'] == 0) {

      Get.back();
      if(payScene.value == PayScene.fromAdoptOrder) {
        Get.offNamed(XinHeRoutes.adoptRecords);

      }
      launchWebUrl('alipays://platformapi/startapp?saId=10000007&qrcode=' + result.data['data']);

    }else {
      XinHeToast.center(result.data['message']);

    }


    }

  Future<void> launchWebUrl(String url) async {
    final Uri uri = Uri.parse(url);
    if (await canLaunchUrl(uri)) {
      await launchUrl(uri, mode: LaunchMode.externalApplication);
    } else {
      XinHeToast.center('请下载支付宝');
    }
  }


}
